#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main (int argc, char *argv[])
{
	FILE *fp = NULL;

	unsigned char *buffer;
	unsigned int range;

	if (argc != 5)
	{
		printf("extract_bin\nGreg Kennedy 2012\npart of the MisCopter project\nhttp://code.google.com/p/miscopter\n\nUsage: %s <input_file> <start> <range> <output_file>\n",argv[0]);
		exit(-1);
	}

	// Step 1: open file, read buffer
	fp = fopen(argv[1],"rb");
	if (!fp)
	{
		printf("Error: could not open %s\n",argv[1]);
		perror("Error reported was");
		exit(-1);
	}
	fseek(fp,atoi(argv[2]),SEEK_SET);
	range = atoi(argv[3]);

	buffer = malloc(range);
	
	if (range != fread(buffer,1,range,fp))
	{
		printf("Error: failed to read %d bytes from %s\n",range,argv[1]);
		exit(-1);
	}
	fclose(fp);

	// Step 2: open and dump file
	fp = fopen(argv[4],"wb");
	if (!fp)
	{
		printf("Error: could not open %s\n",argv[4]);
		perror("Error reported was");
		exit(-1);
	}
	fwrite(buffer,1,range,fp);
	fclose(fp);

	return 0;
}
